<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<c:set var="servicer" value="${sessionScope.servicer}" />
<c:set var="user" value="${sessionScope.user}" />
<c:set value="${pageContext.request.contextPath}" var="path" scope="page"/>

<html lang="en">

<head>
    <title>聊天窗口</title>
    <!-- CSS -->
    <link rel="stylesheet" href="${path}/pet/chat/css/bundle.css">
    <link rel="stylesheet" href="${path}/pet/chat/css/app.min.css">
    <!-- jquery -->
    <script src="${path}/pet/chat/js/bundle.js"></script>
    <script src="${path}/pet/chat/js/app.min.js"></script>
    <script src="${path}/pet/chat/js/examples.js"></script>
</head>

<body>
<div class="page-loading"></div>
<div class="body-plate"></div>

<%-- 导航栏 --%>
<header class="main-header">
    <div id="logo">
        <li><a href="${path}/home">首页</a></li>
        <li><a href="${path}/myOrders">订单</a></li>
        <li><a href="${path}/myAccount">我的</a></li>
    </div>
    <%--<div id="kfgl" style="font-size: 17px;"></div>--%>
    <div id="fmsg" style="font-size: 17px;margin-right: 17%;display: none;" ></div>
    <div id="test" style="font-size: 17px;margin-left: -20%;margin-right: 6%;display: none;"></div>
        <%--好友<label></label>--%>
    <div class="header-nav">
        <ul class="nav">
            <li id="tips_number"></li>
            <%--<li>我的专属客服</li>--%>
            <li><a id="friend" data-navigation-target="friends">好友</a></li>
            <li><a id="chat_msg" data-navigation-target="chat_message">聊天信息<span id="badge2" style="display: none;"></span></a></li>
            <li><a id="add_friend" data-toggle="modal" data-target="#addFriends">添加好友</a></li>
        </ul>
    </div>
</header>

<!-- 添加好友 -->
<div class="modal fade" id="addFriends" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-zoom" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加好友</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <a id="close_w" href="#" class="btn btn-danger sidebar-close">
                        <i data-feather="x"></i>
                    </a>
                </button>
            </div>
            <div class="add_friend">
                <div class="modal-body">
                    <form>
                        <div class="form-group">
                            <label for="username" class="col-form-label">用户名<span id="remind"></span></label>
                            <div>
                                <input type="text" class="form-control" id="username" placeholder="请输入用户名">
                                <button id="submit" type="button" class="btn btn-primary">查询用户</button>
                                <div id="username_3" style="color: #FD3F31;display: none;float: left;">用户名不能为空</div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-body" id="check_result"></div>
            </div>
        </div>
    </div>
</div>

<%--展示提示信息--%>
<div class="modal fade" id="shwoTips" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-zoom" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">提示信息<span id="badge1" style="display: none;"></span></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <a href="#" class="btn btn-danger sidebar-close">
                        <i data-feather="x"></i>
                    </a>
                </button>
            </div>
            <div class="add_friend">
                <div>
                    <label for="username" class="col-form-label" style="margin-left: 6%;">待处理信息</label>
                    <div class="modal-body" id="show_tips1" style="margin-top: -5%;"></div>
                </div>
                <div>
                    <label for="username" class="col-form-label" style="margin-left: 6%;">被拒绝信息</label>
                    <div class="modal-body" id="show_tips2" style="margin-top: -5%;"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="layout">
    <div class="content">
        <!-- 好友列表 -->
        <div id="friends" class="sidebar">
            <header>
                <span>朋友</span>
                <ul class="list-inline">
                    <li class="list-inline-item">
                        <a id="closeBtn" href="#" class="btn btn-danger sidebar-close"><i data-feather="x"></i></a>
                    </li>
                </ul>
            </header>
            <%--<form>--%>
                <%--<input type="text" class="form-control" placeholder="Search">--%>
            <%--</form>--%>
            <div class="sidebar-body">
                <div id="friend_length"></div>
                <div>
                    <ul class="list-group list-group-flush" id="show_friend"></ul>
                </div>
            </div>
        </div>

        <%-- 聊天列表 --%>
        <div id="chat_message" class="sidebar">
            <header>
                <span>聊天</span>
                <ul class="list-inline">
                    <li class="list-inline-item">
                        <a href="#" class="btn btn-danger sidebar-close"><i data-feather="x"></i></a>
                    </li>
                </ul>
            </header>
            <div class="sidebar-body">
                <%--聊天列表--%>
                <ul class="list-group list-group-flush" id="msg_list"></ul>
            </div>
        </div>

        <!-- 聊天框 -->
        <div class="chat" id="chat_k" style="max-width: 1200px;margin: 0 auto;">
            <%--聊天内容--%>
            <div class="chat-body" id="sender_receive_msg"></div>
            <div class="chat-footer">
                <form>
                    <input id="write_msg" type="text" class="form-control" autocomplete="off">
                    <div class="form-buttons">
                        <button class="btn btn-primary" type="submit" id="send_msg">
                            <i data-feather="send"></i>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</body>

<script>
    <%--新加--%>
    var websocket = null;
    var user="<%=session.getAttribute("user")%>";
    var uid = ${user.id};
    var fId = "";
    var friendId_01="";
    var friendId_02="";
    var servicer = "<%=session.getAttribute("servicer")%>";
    console.log(servicer);
    var role = "${param.role}";
    var role1 = "${servicer.role}";
    var cid = "${servicer.id}";
    var s_username = "${servicer.username}";
    var chatSid = "";
    var chatRid = "";
    var chat_k1 = "";
    var num = "";

    //时间戳转换为时间
    function timestampToTime(timestamp) {
        var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = date.getDate() + ' ';
        var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();
        return Y+M+D+h+m+s;
    }

    if(role == "kf") {
        var str0 = '<span style="font-size: 17px;">客服：'+ s_username +'</span>';
        chatRid = cid;
        $('#test').show();
        $('#test').html(str0);
        $('.nav').hide();
        $.ajax({
            type: 'POST',
            url: '/message/selectAll',
            dataType: "json",
            data: {sid: uid, rid: cid},
            error: function () {
                console.log("失败");
            },
            success: function (result) {
                console.log(result);
                $('#sender_receive_msg').empty();
                $("#sender_receive_msg").scrollTop($("#sender_receive_msg")[0].scrollHeight);
                for(var key in result){
                    var str1 = "";
                    if(result[key].receiver.id != uid){
                        chatRid = result[key].receiver.id;   //接受者ID
                        str1 += '<ul class="list-group list-group-flush">';
                        str1 += '    <li class="list-group-item" style="border: 0px;">';
                        str1 += '        <div class="messages">';
                        str1 += '            <div class="message-item outgoing-message" >';
                        str1 += '                <div class="message-avatar">';
                        str1 += '                    <figure class="avatar" title="Mirabelle Tow">';
                        str1 += '                        <img src="${path}/avatar/${user.headUrl}" class="rounded-circle" alt="image">';
                        str1 += '                    </figure>';
                        str1 += '                </div>';
                        str1 += '                <div style="margin-top:-15%;">';
                        str1 += '                    <div class="time">'+ "${user.username}" +'</div>';
                        str1 += '                    <div style="display: table;" class="message-content">'+ result[key].message +'</div>';
                        str1 += '                    <div class="time" >'+ timestampToTime(result[key].createDate) +'</div>';
                        str1 += '                </div>';
                        str1 += '            </div>';
                        str1 += '        </div>';
                        str1 += '    </li>';
                        str1 += '</ul>';
                    } else {
                        str1 += '<ul class="list-group list-group-flush">';
                        str1 += '    <li class="list-group-item" style="border: 0px;">';
                        str1 += '        <div class="messages">';
                        str1 += '            <div class="message-item">';
                        str1 += '                <div class="message-avatar">';
                        str1 += '                    <figure class="avatar" title="Byrom Guittet">';
                        str1 += '                        <img src="${path}/avatar/'+ result[key].receiver.headUrl +'" class="rounded-circle" alt="image">';
                        str1 += '                    </figure>';
                        str1 += '                </div>';
                        str1 += '                <div style="margin-top:-15%;">';
                        str1 += '                    <div class="time" style="text-align: left;">'+ s_username +'</div>';
                        str1 += '                    <div style="display: table;" class="message-content">'+ result[key].message +'</div>';
                        str1 += '                    <div class="time" style="float:left;">'+ timestampToTime(result[key].createDate) +'</div>';
                        str1 += '                </div>';
                        str1 += '            </div>';
                        str1 += '        </div>';
                        str1 += '    </li>';
                        str1 += '</ul>';
                    }
                    $('#sender_receive_msg').append(str1);
                    $("#sender_receive_msg").scrollTop($("#sender_receive_msg")[0].scrollHeight);
                }
            }
        });
    } else if(role == "kfjs") {
        var str1 = "";
        str1 += '<li id="exitlogin"><a style="width: 100px !important;">退出登录</a></li>';
        str1 += '<li><a id="jump" style="width: 150px !important;margin-left: 60%;font-size: 18px;">前往管理系统</a></li>';
        $('#test').show();
        $('#test').html('我是客服：<label>'+ "${user.username}" +'</label>');
//        $('#kfgl').html('');
        $('#logo').html(str1);
        $('#tips_number').hide();
        $('#friend').hide();
        $('#add_friend').hide();
        $('#chat_k').hide();

        $("#jump").click(function(){
            <%--window.location.href = '${path}/loginAdmin';--%>
            window.open('${path}/loginAdmin');
        });


        $("#exitlogin").click(function(){
            if(confirm('确定要退出登录吗?')) {
                var username = "${user.username}";
                $.ajax({
                    type: 'POST',
                    url: '/user/logout',
                    dataType: "json",
                    data: {username:username},
                    error: function () {
                        console.log("失败");
                    },
                    success: function (data) {
                        alert("已退出账号，如有需要，请重新登录");
                        window.location.href = '${path}/login';
                    }
                });
                return true;
            }
            return false;
        });
    } else {
        $('#chat_k').hide();
        chat_k1 = "已隐藏";
    }

    $(document).ready(function() {

        //新建websocket连接
        websocket = new WebSocket("ws://localhost:80/websocket/"+uid);
        //关闭窗口时，断开websocket连接
        window.onbeforeunload = function() {
            websocket.close();
        };
        //连接发生错误
        websocket.onerror = function () {
            console.log("WebSocket连接发生错误");
        };
        //连接成功建立
        websocket.onopen = function () {
            console.log("WebSocket连接成功");
        };
        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            var str =eval('('+ event.data+')');
            console.log(str);
            if(str.type=="发送请求"||str.type=="拒绝请求") {
                document.all['tip'].style.color = "#ff0000";    //提示信息变色
                $.ajax({
                    url: '/message/longSearch',
                    data: {uid:uid},
                    dataType:'json',
                    type: 'POST',
                    success: function (result) {
                        num = result.好友请求的数目 + result.好友拒绝的数目;
                        if (num == "0") {
                            $("#badge1").hide();
                        } else {
                            $("#badge1").show();
                            $("#badge1").html(num);
                        }
                    }
                });
            } else {
                var data =eval('('+ event.data+')');
                console.log(data);
                if(data.type=="聊天"||data.type=="售后"||data.type=="咨询"){
                    var str1 = "";
                    str1 += '<ul class="list-group list-group-flush">';
                    str1 += '    <li class="list-group-item" style="border: 0px;">';
                    str1 += '        <div class="messages">';
                    str1 += '            <div class="message-item">';
                    str1 += '                <div class="message-avatar">';
                    str1 += '                    <figure class="avatar" title="Byrom Guittet">';
                    str1 += '                        <img src="${path}/avatar/'+ data.url +'" class="rounded-circle" alt="image">';
                    str1 += '                    </figure>';
                    str1 += '                </div>';
                    str1 += '                <div style="margin-top: -15%">';
                    str1 += '                    <div class="time" style="text-align: left">'+ data.username +'</div>';
                    str1 += '                    <div style="display: table;" class="message-content">'+ data.content +'</div>';
                    str1 += '                    <div class="time" >'+ timestampToTime(data.messageDate) +'</div>';
                    str1 += '                </div>';
                    str1 += '            </div>';
                    str1 += '        </div>';
                    str1 += '    </li>';
                    str1 += '</ul>';
                    $('#sender_receive_msg').append(str1);
                    $("#sender_receive_msg").scrollTop($("#sender_receive_msg")[0].scrollHeight);
                    var mid = data.messageId;
                    //查询未读信息数目
                    if($("#chat_k").is(":hidden")){
                        console.log("聊天框已隐藏");
                        $.ajax({
                            url: '/message/longSearch',
                            data: {uid:uid},
                            dataType:'json',
                            type: 'POST',
                            success: function (result) {
                                if(result.未读消息数目 == "0"){
                                    $("#badge2").hide();
                                } else {
                                    document.all['chat_msg'].style.color = "#ff0000";    //提示信息变色
                                    $("#badge2").show();
                                    $("#badge2").html(result.未读消息数目);
                                }
                            }
                        });
                    } else {
                        //更新信息状态
                        $.ajax({
                            type: 'POST',
                            url: '/message/updateState',
                            dataType: "json",
                            data: {mid:mid},
                            error: function () {
                                console.log("失败");
                            },
                            success: function () {
                                console.log("成功");
                            }
                        });
                    }
                }
            }
        };

        //查询全部好友
        var friendId="";
        $("#friend").click(function() {
            $.ajax({
                type: 'POST',
                url: '/friend/selectAllFriend',
                dataType: "json",
                async: false,
                data: {},
                error: function () {
                    alert("失败");
                },
                success: function (result) {
                    var test = "";
                    var str = "";
                    for(var key in result){
                        str += '<li class="list-group-item friend '+result[key].friend.id+'" id="'+result[key].friend.id+'">';
                        str += '    <figure class="avatar">';
                        str += '        <img src="${path}/avatar/'+ result[key].friend.headUrl +'" class="rounded-circle" alt="image">';
                        str += '    </figure>';
                        str += '    <div class="users-list-body">';
                        str += '        <div id="show_fname">';
                        str += '            <h5 id="friendId" style="margin-top:4%;">'+ result[key].friend.username +'</h5>';
                        str += '        </div>';
                        str += '        <a data-toggle="dropdown" href="#">更多</a>';
                        str += '        <div class="dropdown-menu dropdown-menu-right">';
                        str += '            <a id="'+ result[key].id +'" class="dropdown-item delete">删除好友</a>';
                        str += '            <a name="'+ result[key].friend.username +'" id="'+ result[key].friend.id +'" href="#" class="dropdown-item new_chat">新的聊天</a>';
                        str += '        </div>';
                        str += '    </div>';
                        str += '</li>';
                        $('#show_friend').html(str);
                    }
                    websocket.onmessage = function (event) {
                        var str =eval('('+ event.data+')');
                        if(str.type=="删除"){
                            for(i=0; i<result.length; i++) {
                                if(str.sid == result[i].friend.id){
                                    test = $("#show_friend .list-group-item.friend").attr('id');
                                    console.log(test);
                                    $("."+test).empty();
                                }
                            }
                        } else if(str.type=="聊天"||str.type=="售后"||str.type=="咨询"){
                            var data =eval('('+ event.data+')');
                            console.log(data);
                            if(data.type=="聊天"||data.type=="售后"||data.type=="咨询"){
                                if($("#chat_k").is(":hidden")){
                                    //查询未读消息
                                    $.ajax({
                                        url: '/message/longSearch',
                                        data: {uid:uid},
                                        dataType:'json',
                                        type: 'POST',
                                        success: function (result) {
                                            if($("#chat_k").is(":hidden")) {
                                                if (result.未读消息数目 == "0") {
                                                    $("#badge2").hide();
                                                } else {
                                                    document.all['chat_msg'].style.color = "#ff0000";    //提示信息变色
                                                    $("#badge2").show();
                                                    $("#badge2").html(result.未读消息数目);
                                                }
                                            } else {
                                                console.log("聊天框为隐藏");
                                            }
                                        }
                                    });
                                } else {
                                    var mid1 = data.messageId;
                                    //更新信息状态
                                    $.ajax({
                                        type: 'POST',
                                        url: '/message/updateState',
                                        dataType: "json",
                                        data: {mid:mid1},
                                        error: function () {
                                            console.log("失败");
                                        },
                                        success: function () {
                                            console.log("成功");
                                        }
                                    });
                                }

                                console.log("test");
                                var str1 = "";
                                str1 += '<ul class="list-group list-group-flush">';
                                str1 += '    <li class="list-group-item" style="border: 0px;">';
                                str1 += '        <div class="messages">';
                                str1 += '            <div class="message-item">';
                                str1 += '                <div class="message-avatar">';
                                str1 += '                    <figure class="avatar" title="Byrom Guittet">';
                                str1 += '                        <img src="${path}/avatar/'+ data.url +'" class="rounded-circle" alt="image">';
                                str1 += '                    </figure>';
                                str1 += '                </div>';
                                str1 += '                <div style="margin-top:-15%;">';
                                str1 += '                    <div class="time" style="text-align: left;">'+ data.username +'</div>';
                                str1 += '                    <div style="display: table;" class="message-content">'+ data.content +'</div>';
                                str1 += '                    <div class="time" >'+ timestampToTime(data.messageDate) +'</div>';
                                str1 += '                </div>';
                                str1 += '            </div>';
                                str1 += '        </div>';
                                str1 += '    </li>';
                                str1 += '</ul>';
                                $('#sender_receive_msg').append(str1);
                                $("#sender_receive_msg").scrollTop($("#sender_receive_msg")[0].scrollHeight);
                            }
                        }
                    };

                    //新的聊天
                    $("#show_friend .dropdown-item.new_chat").click(function() {
                        $('#fmsg').show();
                        $('#test').hide();
                        $('#chat_k').show();
                        fId = $(this).attr('id');
                        var f_name = $(this).attr('name');
                        $('#fmsg').html('好友：<label style="width: 150px;">'+ $(this).attr('name') +'<a id="close_chat" style="float:right;">关闭聊天框</a></label>');
                        $("#close_chat").click(function() {
                            $('#chat_k').hide();
                            $('#fmsg').hide();
                            $('#test').hide();
                        });
                        chatRid = fId;
                        $.ajax({
                            type: 'POST',
                            url: '/message/selectAll',
                            dataType: "json",
                            data: {sid: uid, rid: fId},
                            error: function () {
                                console.log("失败");
                            },
                            success: function (result) {
                                //修改信息的状态
                                $.ajax({
                                    type: 'POST',
                                    url: '/message/changeStates',
                                    dataType: "json",
                                    data: {uid:uid,rid:fId},
                                    error: function () {
                                        console.log("changeStates随便吧");
                                    },
                                    success: function () {
                                        console.log("changeStates成功");
                                    }
                                });
                                console.log(result);
                                $('#sender_receive_msg').empty();
                                $("#sender_receive_msg").scrollTop($("#sender_receive_msg")[0].scrollHeight);
                                for(var key in result){
                                    var str1 = "";
                                    if(result[key].receiver.id != uid){
                                        str1 += '<ul class="list-group list-group-flush">';
                                        str1 += '    <li class="list-group-item" style="border: 0px;">';
                                        str1 += '        <div class="messages">';
                                        str1 += '            <div class="message-item outgoing-message" >';
                                        str1 += '                <div class="message-avatar">';
                                        str1 += '                    <figure class="avatar" title="Mirabelle Tow">';
                                        str1 += '                        <img src="${path}/avatar/${user.headUrl}" class="rounded-circle" alt="image">';
                                        str1 += '                    </figure>';
                                        str1 += '                </div>';
                                        str1 += '                <div style="margin-top:-15%;">';
                                        str1 += '                    <div class="time">'+ "${user.username}" +'</div>';
                                        str1 += '                    <div style="display: table;" class="message-content">'+ result[key].message +'</div>';
                                        str1 += '                    <div class="time" >'+ timestampToTime(result[key].createDate) +'</div>';
                                        str1 += '                </div>';
                                        str1 += '            </div>';
                                        str1 += '        </div>';
                                        str1 += '    </li>';
                                        str1 += '</ul>';
                                    } else {
                                        console.log(result[key]);
                                        str1 += '<ul class="list-group list-group-flush">';
                                        str1 += '    <li class="list-group-item" style="border: 0px;">';
                                        str1 += '        <div class="messages">';
                                        str1 += '            <div class="message-item">';
                                        str1 += '                <div class="message-avatar">';
                                        str1 += '                    <figure class="avatar" title="Byrom Guittet">';
                                        str1 += '                        <img src="${path}/avatar/'+ result[key].receiver.headUrl +'" class="rounded-circle" alt="image">';
                                        str1 += '                    </figure>';
                                        str1 += '                </div>';
                                        str1 += '                <div style="margin-top:-15%;">';
                                        str1 += '                    <div class="time" style="text-align: left;">'+ f_name +'</div>';
                                        str1 += '                    <div style="display: table;" class="message-content">'+ result[key].message +'</div>';
                                        str1 += '                    <div class="time" >'+ timestampToTime(result[key].createDate) +'</div>';
                                        str1 += '                </div>';
                                        str1 += '            </div>';
                                        str1 += '        </div>';
                                        str1 += '    </li>';
                                        str1 += '</ul>';
                                    }
                                    $('#sender_receive_msg').append(str1);
                                    $("#sender_receive_msg").scrollTop($("#sender_receive_msg")[0].scrollHeight);
                                }
                            }
                        });
                    });
                    //删除好友——必须有双向数据
                    $("#show_friend .dropdown-item.delete").click(function() {
                        fId = $(this).attr('id');
                        console.log(fId);
                        console.log(uid);
                        $.ajax({
                            type: 'POST',
                            url: '/friend/deleteFriend',
                            dataType: "json",
                            data: {friendId:fId,uid:uid},
                            error: function () {
                                console.log("失败");
                            },
                            success: function (result) {
                                if(result.msg == "删除好友成功"){
                                    var msg01={
                                        sid:uid,//当前操作用户得id
                                        rid:result.fid,//对方id
                                        type:"删除",
                                        content:"用户rid被sid删除了，rid接收到信号需要重新调用一次selectAllFriends"
                                    };
                                    websocket.send(JSON.stringify(msg01));
                                    alert("成功删除好友");
                                    var test1 = result.fid;
                                    console.log(test1);
                                    $("."+test1).empty();
                                    return false;
                                } else {
                                    alert("删除好友失败");
                                }
                            }
                        });
                    });
                }

            });
        });

        //点击发送信息
        $("#send_msg").click(function() {
            var write_msg = $.trim($("#write_msg").val());
            $('#write_msg').val("");
            if(chatRid != "" || role =="kf") {
                var msg = {
                    "sid":uid,
                    "rid":chatRid,
                    "content":write_msg,
                    "type":"聊天"
                };
            } else if(role =="kfjs") {
                var msg = {
                    "sid":uid,
                    "rid":ffId,
                    "content":write_msg,
                    "type":"聊天"
                };
            }
            websocket.send(JSON.stringify(msg));
            //获取发送消息的时间点
            var date = new Date();
            var dateArr = [date.getHours(),date.getMinutes(),date.getSeconds()];
            for(var i=0;i<dateArr.length;i++){
                if (dateArr[i] >= 1 && dateArr[i] <= 9) {
                    dateArr[i] = "0" + dateArr[i];
                }
            }
            var str1 = "";
            str1 += '<ul class="list-group list-group-flush">';
            str1 += '    <li class="list-group-item" style="border: 0px;">';
            str1 += '        <div class="messages">';
            str1 += '            <div class="message-item outgoing-message" >';
            str1 += '                <div class="message-avatar">';
            str1 += '                    <figure class="avatar" title="Mirabelle Tow">';
            str1 += '                        <img src="${path}/avatar/${user.headUrl}" class="rounded-circle" alt="image">';
            str1 += '                    </figure>';
            str1 += '                </div>';
            str1 += '                <div style="margin-top:-15%;">';
            str1 += '                    <div class="time">'+ "${user.username}" +'</div>';
            str1 += '                    <div class="message-content">'+ write_msg +'</div>';
            str1 += '                    <div id="dates" class="time">'+ dateArr[0]+':'+dateArr[1]+':'+dateArr[2] +'</div>';
            str1 += '                </div>';
            str1 += '            </div>';
            str1 += '        </div>';
            str1 += '    </li>';
            str1 += '</ul>';
            $('#sender_receive_msg').append(str1);
            $("#sender_receive_msg").scrollTop($("#sender_receive_msg")[0].scrollHeight);
            return false;
        });

        var ffId = "";
        var ffname = "";
        //查询该用户聊天信息列表
        $("#chat_msg").click(function() {
            console.log(uid);
            $.ajax({
                type: 'POST',
                url: '/message/selectUnRead',
                dataType: "json",
                data: {uid:uid},
                error: function () {
                    console.log("失败");
                },
                success: function (result) {
                    var str = "";
                    for(var key in result){
                        console.log(result[key]);
                        var msg_count = "";
                        if(result[key].unreadCount == undefined){
                            console.log("未定义");
                            msg_count = "";
                        } else {
                            msg_count = result[key].unreadCount;
                        }
                        ffId = result[key].latestMessage.sender.id;
                        ffname = result[key].latestMessage.sender.username;
                        str += '<li class="list-group-item" style="'+ result[key].latestMessage.sender.id +'" id="'+ result[key].latestMessage.sender.username +'">';
                        str += '    <figure class="avatar avatar-state-success">';
                        str += '        <img src="${path}/avatar/'+ result[key].latestMessage.sender.headUrl +'" class="rounded-circle" alt="image">';
                        str += '    </figure>';
                        str += '    <div class="users-list-body">';
                        str += '        <div>';
                        str += '            <h5 class="text-primary">'+ result[key].latestMessage.sender.username +'</h5>';
                        str += '            <p>'+ result[key].latestMessage.message +'</p>';
                        str += '        </div>';
                        str += '        <div class="user5s-list-action">';
                        str += '            <small class="text-primary" style="display: table;">'+ timestampToTime(result[key].latestMessage.createDate) +'</small>';
                        str += '            <div id="msg_count" class="new-message-count">'+ msg_count +'</div>';
                        str += '        </div>';
                        str += '    </div>';
                        str += '</li>';
                        $('#msg_list').html(str);
                    }
                    //点击聊天列表的某个用户
                    $("#msg_list .list-group-item").click(function() {
                        ffId = $(this).attr('style');
                        chatRid = ffId;
                        ffname = $(this).attr('id');
                        console.log(ffId);
                        $('#test').hide();
                        $('#chat_k').show();
                        $('#fmsg').html('好友：<label style="width: 150px;">'+ ffname +'<a id="close_chat" style="float:right;">关闭聊天框</a></label>');
                        $("#close_chat").click(function() {
                            $('#chat_k').hide();
                            $('#fmsg').hide();
                            $('#test').hide();
                        });
                        //点击该用户后，查询两者所有的聊天信息
                        $.ajax({
                            type: 'POST',
                            url: '/message/selectAll',
                            dataType: "json",
                            data: {sid: uid, rid: ffId},
                            error: function () {
                                console.log("失败");
                            },
                            success: function (result) {
                                $('#chat_k').show();
                                $('#fmsg').show();
                                $('#test').hide();
                                console.log(result);
                                $('#sender_receive_msg').empty();
                                $("#sender_receive_msg").scrollTop($("#sender_receive_msg")[0].scrollHeight);
                                for(var key in result){
                                    var str1 = "";
                                    if(result[key].receiver.id != uid){
//                                        chatRid = result[key].receiver.id;   //接受者ID
                                        str1 += '<ul class="list-group list-group-flush">';
                                        str1 += '    <li class="list-group-item" style="border: 0px;">';
                                        str1 += '        <div class="messages">';
                                        str1 += '            <div class="message-item outgoing-message" >';
                                        str1 += '                <div class="message-avatar">';
                                        str1 += '                    <figure class="avatar" title="Mirabelle Tow">';
                                        str1 += '                        <img src="${path}/avatar/${user.headUrl}" class="rounded-circle" alt="image">';
                                        str1 += '                    </figure>';
                                        str1 += '                </div>';
                                        str1 += '                <div style="margin-top:-15%;">';
                                        str1 += '                    <div class="time">'+ "${user.username}" +'</div>';
                                        str1 += '                    <div class="message-content">'+ result[key].message +'</div>';
                                        str1 += '                    <div class="time" >'+ timestampToTime(result[key].createDate) +'</div>';
                                        str1 += '                </div>';
                                        str1 += '            </div>';
                                        str1 += '        </div>';
                                        str1 += '    </li>';
                                        str1 += '</ul>';
                                    } else {
                                        str1 += '<ul class="list-group list-group-flush">';
                                        str1 += '    <li class="list-group-item" style="border: 0px;">';
                                        str1 += '        <div class="messages">';
                                        str1 += '            <div class="message-item">';
                                        str1 += '                <div class="message-avatar">';
                                        str1 += '                    <figure class="avatar" title="Byrom Guittet">';
                                        str1 += '                        <img src="${path}/avatar/'+ result[key].receiver.headUrl +'" class="rounded-circle" alt="image">';
                                        str1 += '                    </figure>';
                                        str1 += '                </div>';
                                        str1 += '                <div style="margin-top:-15%;">';
                                        str1 += '                    <div class="time" style="text-align: left">'+ ffname +'</div>';
                                        str1 += '                    <div class="message-content" style="display: table;">'+ result[key].message +'</div>';
                                        str1 += '                    <div class="time" style="text-align: left;">'+ timestampToTime(result[key].createDate) +'</div>';
                                        str1 += '                </div>';
                                        str1 += '            </div>';
                                        str1 += '        </div>';
                                        str1 += '    </li>';
                                        str1 += '</ul>';
                                    }
                                    $('#sender_receive_msg').append(str1);
                                    $("#sender_receive_msg").scrollTop($("#sender_receive_msg")[0].scrollHeight);
                                }
                                //修改信息的状态
                                $.ajax({
                                    type: 'POST',
                                    url: '/message/changeStates',
                                    dataType: "json",
                                    data: {uid:uid,rid:ffId},
                                    error: function () {
                                        document.all['chat_msg'].style.color = "#000000";    //提示信息变色
                                            $.ajax({
                                                url: '/message/longSearch',
                                                data: {uid: uid},
                                                dataType: 'json',
                                                type: 'POST',
                                                success: function (result) {
                                                    if (result.未读消息数目 == "0") {
                                                        $("#badge2").hide();
                                                    } else {
                                                        $("#badge2").show();
                                                        $("#badge2").html(result.未读消息数目);
                                                    }
                                                }
                                            });
                                    },
                                    success: function () {
                                        console.log("changeStates成功");
                                    }
                                });
                            }
                        });
                    });
                }
            });
        });

        //点击添加好友按钮
        $("#add_friend").click(function() {
            $("#username").val("");
            $('#check_result').empty();
            $("#username_3").hide();
        });
        $("#username").focus(function(){
            $("#username_3").hide();
        });

        //查询所加好友是否存在
        $("#submit").click(function() {
            var username = $.trim($("#username").val());
            if(username==""){
                $("#username_3").toggle();
            }else{
                $.ajax({
                    type: 'POST',
                    url: '/friend/findFriend',
                    dataType: "json",
                    data: {username:username},
                    error: function () {
                        alert("失败");
                    },
                    success: function(result) {
                        console.log(result);
                        //验证用户名是否存在
                        if(result.msg == "not_exist") {
                            alert("用户不存在，请重新输入");
                        } else {
                            var str = "";
                            str += '<div class="check_f">';
                            str += '    <ul class="list-group list-group-flush" id="show_result">';
                            str += '        <li class="list-group-item">';
                            str += '            <figure class="avatar">';
                            str += '                <img src="${path}/avatar/'+ result.headUrl +'" class="rounded-circle" alt="image">';
                            str += '            </figure>';
                            str += '            <div class="users-list-body">';
                            str += '                <h5 id="friendId">'+ result.username +'</h5>';
                            str += '            </div>';
                            str += '        </li>';
                            str += '    </ul>';
                            str += '</div>';
                            str += '<input id="send" value="确认发送好友请求" class="btn btn-primary" type="button" />';
                            $('#check_result').html(str);
                            $("#send").click(function() {
                                fId = result.id;
                                //发送添加请求
                                $.ajax({
                                    type: 'POST',
                                    url: '/friend/sendRequest',
                                    dataType: "json",
                                    data: {fid:fId},
                                    error: function () {
                                        alert("未能成功发送好友请求");
                                    },
                                    success: function (result) {
                                        if(result.msg=="发送好友请求成功"){
                                            alert("发送请求成功");
                                            $("#send").val("已成功发送请求");
                                            var msg = {
                                                "sid": uid,
                                                "rid":fId,
                                                "content":"你好！",
                                                "type":"发送请求"
                                            };
                                            websocket.send(JSON.stringify(msg));
                                        }
                                        if(result.msg=="你们已经是好友"){
                                            alert("你们已经是好友");
                                        }
                                        if(result.msg=="已向用户发送过好友请求"){
                                            alert("已向用户发送过好友请求");
                                        }
                                        if(result.msg=="对方已请求"){
                                            alert("该用户已经向您发送了请求，请查看！");
                                        }
                                        if(result.msg=="发送好友请求失败"){
                                            alert("发送好友请求失败");
                                        }
                                    }
                                });
                            });
                        }
                    }
                });
            }
        });


        //提示信息的变化
        $.ajax({
            type: 'POST',
            url: '/friend/findTip',
            async: false,
            dataType: "json",
            data: {},
            error: function () {
                alert("失败");
            },
            success: function (result) {
                var str = "";
                console.log(result);
                if(result.length == "0"){
                    str += '<a id="tip" data-toggle="modal" data-target="#shwoTips">提示信息<span id="badge1" style="display: none;"></span></a>';
                    $('#tips_number').html(str);
                } else {
                    str += '<a id="tip" data-toggle="modal" data-target="#shwoTips" style="color:#F61F1F;">提示信息<span id="badge1" style="display: none;"></span></a>';
                    $('#tips_number').html(str);
                }
            }
        });
        //查询未读消息
        $.ajax({
            url: '/message/longSearch',
            data: {uid:uid},
            dataType:'json',
            type: 'POST',
            success: function (result) {
                console.log(result.未读消息数目);
                if(result.未读消息数目 == "0"){
                    $("#badge2").hide();
                } else {
                    $("#badge2").show();
                    $("#badge2").html(result.未读消息数目);
                    document.all['chat_msg'].style.color = "#ff0000";    //提示信息变色
                }
            }
        });
        //查询提示消息
        $.ajax({
            url: '/message/longSearch',
            data: {uid:uid},
            dataType:'json',
            type: 'POST',
            success: function (result) {
                console.log(result.未读消息数目);
                num = result.好友请求的数目 + result.好友拒绝的数目;
                if(num == "0"){
                    $("#badge1").hide();
                } else {
                    $("#badge1").show();
                    $("#badge1").html(num);
                }
            }
        });


        //点击“提示信息”
        $("#tip").click(function() {
            console.log("有效果吗");
            $.ajax({
                type: 'POST',
                url: '/friend/findTip',
                dataType: "json",
                data: {},
                error: function () {
                    alert("失败");
                },
                success: function (result) {
                    console.log(result);
                    //更改提示信息的状态
                    var str2 = "";
                    str2 += '<a id="tip" data-toggle="modal" data-target="#shwoTips">提示信息<span id="badge1" style="display: none;"></span></a>';
                    $('#tips_number').html(str2);
                    var str = "";
                    var str1 = "";
                    for(var key in result){
                        if(result[key].state == "已发送"){
                            console.log(result[key]);
                            //新加
                            str += '<div class="check_f">';
                            str += '    <ul class="list-group list-group-flush">';
                            str += '        <li class="list-group-item" style="border-bottom: 1px solid #ebebeb;">';
                            str += '            <figure class="avatar">';
                            str += '                <img src="${path}/avatar/'+ result[key].user.headUrl +'" class="rounded-circle" alt="image">';
                            str += '            </figure>';
                            str += '            <div class="users-list-body">';
                            str += '                <h5 id="'+ result[key].id +'" style="margin-top:4%;">'+ result[key].user.username +'</h5>';
                            str += '            </div>';
                            str += '        </li>';
                            str += '    </ul>';
                            str += '</div>';
                            str += '<button type="button" class="btn btn-primary accept_f" style="margin-top: -9%;">接受</button>';
                            str += '<button id="'+ result[key].user.id +'" type="button" class="btn btn-primary refuse_f" style="margin-top: -9%;">拒绝</button>';
                            $('#show_tips1').html(str);
                        } else if(result[key].state == "已拒绝*"){
                            //新加
                            str1 += '<div class="check_f">';
                            str1 += '    <ul class="list-group list-group-flush">';
                            str1 += '        <li class="list-group-item" style="border-bottom: 1px solid #ebebeb;">';
                            str1 += '            <figure class="avatar">';
                            str1 += '                <img src="${path}/avatar/'+ result[key].friend.headUrl +'" class="rounded-circle" alt="image">';
                            str1 += '            </figure>';
                            str1 += '            <div class="users-list-body">';
                            str1 += '                <h5 id="'+ result[key].id +'" style="margin-top:4%;">'+ result[key].friend.username +'</h5>';
                            str1 += '            </div>';
                            str1 += '        </li>';
                            str1 += '    </ul>';
                            str1 += '</div>';
                            str1 += '<button type="button" class="btn btn-primary refuse_confirm" style="margin-top: -9%;">知道了</button>';
                            $('#show_tips2').html(str1);
                        }
                    }
                    //接受好友请求
                    $("#show_tips1 .btn.btn-primary.accept_f").click(function() {
                        friendId_01 = $("#show_tips1 h5").attr('id');
                        $.ajax({
                            type: 'POST',
                            url: '/friend/acceptFriend',
                            dataType: "json",
                            data: {friendId:friendId_01},
                            error: function () {
                                console.log("失败");
                            },
                            success: function (result) {
                                console.log(result);
                                if(result.msg == "添加好友成功"){
                                    location.reload();
                                }
                            }
                        });
                    });
                    //拒绝好友请求
                    $("#show_tips1 .btn.btn-primary.refuse_f").click(function() {
                        friendId_01 = $("#show_tips1 h5").attr('id');
                        var friendId_02 = $(this).attr('id');
                        $.ajax({
                            type: 'POST',
                            url: '/friend/refuseRequest',
                            dataType: "json",
                            data: {friendId:friendId_01},
                            error: function () {
                                console.log("失败");
                            },
                            success: function (result) {
                                if(result.msg == "成功！"){
                                    var msg = {
                                        "sid": uid,
                                        "rid":friendId_02,
                                        "content":"已拒绝",
                                        "type":"拒绝请求"
                                    };
                                    websocket.send(JSON.stringify(msg));
                                    location.reload();
                                }
                            }
                        });
                    });
                    //拒绝好友后。点击“知道了”
                    $("#show_tips2 .btn.btn-primary.refuse_confirm").click(function() {
                        friendId_02 = $("#show_tips2 h5").attr('id');
                        $.ajax({
                            type: 'POST',
                            url: '/friend/refuseConfirm',
                            dataType: "json",
                            data: {friendId:friendId_02},
                            error: function () {
                                console.log("失败");
                            },
                            success: function (result) {
                                if(result.msg == "成功！"){
                                    location.reload();
                                }
                            }
                        });
                    });
                }
            });
        });
    });
</script>
<style>
    #username {
        width: 80%;
        float: left;
    }
    #submit {
        float: right;
    }
    #show_result {
        margin-top: -10%;
        border-bottom: 1px solid #ebebeb;
    }
    #send {
        float: right;
        margin-top: -5%;
    }
    #friendId {
        margin-top:4%;
    }
    .users-list-body {
        float:left;
        margin-left:5%;
        margin-top:1%;
    }
    .avatar {
        float: left;
    }
    .friend {
        padding: 5px;
    }
    .check_f {
        width: 65%;
        display: inline-block;
    }
    #badge1 {
        padding: 2px 5px;  /* 不需要定义height与width，添加合适的padding使圆圈随字符长短变化而改变 */
        line-height: 20px;
        text-align: center;
        background-color: red;
        color: white;
        font-size: 12px;
        font-weight: 700;
        border-radius: 50%;
    }
    #badge2 {
        padding: 2px 5px;  /* 不需要定义height与width，添加合适的padding使圆圈随字符长短变化而改变 */
        line-height: 20px;
        text-align: center;
        background-color: red;
        color: white;
        font-size: 12px;
        font-weight: 700;
        border-radius: 50%;
    }
    #msg_count {
        float: right;
        padding: 2px 5px;
        line-height: 15px;
        text-align: center;
        background-color: #969696;
        color: white;
        font-size: 12px;
        font-weight: 700;
        border-radius: 50%;
    }
</style>


</html>